#!/usr/bin/python

# https://console.cloud.tencent.com/api/explorer

import requests
import json
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.vpc.v20170312 import vpc_client, models


def AddGroupRole(sourceip):
    try:
        cred = credential.Credential("xxx", "xxx")
        httpProfile = HttpProfile()
        httpProfile.endpoint = "vpc.tencentcloudapi.com"

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = vpc_client.VpcClient(cred, "ap-shanghai", clientProfile)

        req = models.CreateSecurityGroupPoliciesRequest()

        params = {
            "SecurityGroupPolicySet": {
                "Ingress": [
                    {
                        "PolicyIndex": 0,
                        "Protocol": "TCP",
                        "Port": "443",
                        "CidrBlock": sourceip,
                        "Action": "ACCEPT",
                        "PolicyDescription": "yian"
                    }
                ]
            },
            "SecurityGroupId": "sg-5x9x4x66"
        }
        req.from_json_string(json.dumps(params))

        resp = client.CreateSecurityGroupPolicies(req)
        print(resp.to_json_string())

    except TencentCloudSDKException as err:
        print(err)


def GetCompanyOldIp():
    try:
        f = open('ip.txt', 'r')
        oldIp = f.read().strip()
        return oldIp
    except IOError:
        print("Error: 没有找到文件或读取文件失败")


def WriteIp(sourceip):
    try:
        f = open('ip.txt', 'r+')
        f.read()
        f.write('\n'+sourceip)
        f.close()
    except IOError:
        print("Error: 没有找到文件或写入文件失败")


if __name__ == '__main__':
    NewIp = requests.get(url="http://ip.42.pl/raw").text
    OldIp = GetCompanyOldIp()
    if NewIp in OldIp:
        print('公网ip没有发生变化')
    else:
        print('公网ip发生变化：', OldIp)
        AddGroupRole(NewIp)
        WriteIp(NewIp)
